//
//  NetWork.m
//  Project
//
//  Created by 冯东辉 on 2018/9/11.
//  Copyright © 2018年 FengDongHui. All rights reserved.
//

#import "NetWork.h"
#import "MJExtension.h"

@implementation NetWork

+(NetWork*)sharedInstance {
    
    static NetWork *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[NetWork alloc] init];
    });
    
    return sharedInstance;
}

/**
 异步Post请求
 
 @param data 当前业务所需数据
 @param timeout 请求超时时间
 @param urlString 请求地址
 @param successed_handler 成功返回
 @param failed_handler 失败返回
 */
-(void)asyncPostHttpRequest:(NSDictionary*)data
                    timeout:(NSTimeInterval)timeout
                  urlMethod:(NSString *)urlString
          successed_handler:(void (^)(NSDictionary* jsonDic))successed_handler
             failed_handler:(void (^)(NSInteger statusCode,NSData* data))failed_handler {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager.requestSerializer setTimeoutInterval:timeout];
    
    [manager POST:urlString parameters:data progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSString *json_str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *json_dic = [json_str mj_JSONObject];
        
        successed_handler(json_dic);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failed_handler(999,nil);
    }];
}

/**
 异步Get请求
 
 @param data 当前业务所需数据
 @param timeout 请求超时时间
 @param urlString 请求地址
 @param successed_handler 成功返回
 @param failed_handler 失败返回
 */
-(void)asyncGetHttpRequest:(NSDictionary*)data
                   timeout:(NSTimeInterval)timeout
                 urlMethod:(NSString *)urlString
         successed_handler:(void (^)(NSDictionary *json))successed_handler
            failed_handler:(void (^)(NSInteger statusCode,NSData* data))failed_handler {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager.requestSerializer setTimeoutInterval:timeout];
    
    [manager GET:urlString parameters:data progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSString *json_str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *json_dic = [json_str mj_JSONObject];
        
        successed_handler(json_dic);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failed_handler(999,nil);
    }];
}

/**
 异步Post请求 上传文件
 
 @param data 当前业务所需数据
 @param fileData 文件数据
 @param fileName 文件名称
 @param timeout 请求超时时间
 @param urlString 请求地址
 @param successed_handler 成功返回
 @param failed_handler 失败返回
 */
-(void)asyncPostHttpRequest:(NSDictionary*)data
                   fileData:(NSArray *)fileData
                   fileName:(NSString *)fileName
                    timeout:(NSTimeInterval)timeout
                  urlMethod:(NSString *)urlString
          successed_handler:(void (^)(NSDictionary* jsonDic))successed_handler
             failed_handler:(void (^)(NSInteger statusCode,NSData* data))failed_handler {
    
    if( timeout < 5 ) {
        timeout = 5;
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager.requestSerializer setTimeoutInterval:timeout];
    
    [manager POST:urlString parameters:data constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (int i = 0; i < fileData.count; i++) {
            
            UIImage *image = fileData[i];
            
            NSData *imageData = UIImageJPEGRepresentation(image, 1);
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *imageName = [NSString stringWithFormat:@"%@_%d.jpg", str, i];
            
            [formData appendPartWithFileData:imageData name:fileName fileName:imageName mimeType:@"image/jpg"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSString *json_str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *json_dic = [json_str mj_JSONObject];
        
        successed_handler(json_dic);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failed_handler(999,nil);
    }];
}

@end
